import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

// 没有token可以访问的白名单
const whiteList = ['/login','/', '/loanapply', '/invest', '/register'] // no redirect whitelist

// 路由守卫
router.beforeEach(async(to, from, next) => {
  console.log('to',to,'from',from)
  // start progress bar
  // 进度条开启
  NProgress.start()

  // set page title
  // 设置页面的标题
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  // 创建一个变量 获取token
  const hasToken = getToken()

  // 如果有token
  if (hasToken) {
    // 如果 路由地址是login的话，但是已经有token的状态，那就路由到根地址'/'
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      // 获取 state下面user模块下面的name
      const hasGetUserInfo = store.getters.name
      // 如果有的话，直接放行
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          // get user info
          // await 将异步操作 变为同步操作 等待获取用户信息
          await store.dispatch('user/getInfo')
          // 如果请求成功的话，就放行
          next()
        } catch (error) {
          // remove token and go to login page to re-login
          // 假如获取不到用户的信息的话，出错，就重置cookie里面的token，并且将store里面的state也重置
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
    
  } else {
    /* has no token*/
    // 如果没有token,就在白名单中查找一下，
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
